<?php

namespace App\Admin\Controllers;

use App\AdminRole;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    //
    public function index()
    {
        $roles = AdminRole::orderBy('created_at', 'desc')->paginate(10);
        return view('admin.role.index', compact('roles'));
    }

    public function create()
    {
        return view('admin.role.add');
    }

    public function store()
    {
        //验证
        $this->validate(\request(), [
            'name' => 'required | string',
            'description' => 'required | String'
        ]);

        $params = \request(['name', 'description']);
         $role = AdminRole::create($params);

        //渲染
        return redirect('admin/roles');
    }

    //权限管理列表
    public function permission(AdminRole $role)
    {
        $permissions = \App\AdminPermission::all();
        $myPermissions = $role->permissions;

        return view("admin.role.permission", compact('permissions', 'myPermissions', 'role'));
    }

    //保存权限
    public function storePermission(AdminRole $role)
    {
        $this->validate(\request(), [
            'permissions' => 'required | array'
        ]);

        //所有选择的权限
        $permissions = \App\AdminPermission::findMany(\request('permissions'));
        //原有的权限
        $myPermissions = $role->permissions;

        //要增加的
        $addPermissions = $permissions->diff($myPermissions);
        foreach($addPermissions as $addPermission) {
            $role->grantPermission($addPermission);
        }

        //要删除的
        $deletePermissions = $myPermissions->diff($permissions);
        foreach($deletePermissions as $deletePermission) {
            $role->deletePermission($deletePermission);
        }

        return back();
    }

}
